package com.ycz.sas.jgen.handler;

import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChooseDirListener implements MouseListener{

	private Component owner;
	private String startPath;
	private String selectedPath;

	public ChooseDirListener(){}

	public ChooseDirListener(Component owner){
		this.owner = owner;
	}

	public ChooseDirListener(Component owner, String path){
		this(owner);
		startPath = path;
	}

	public String getSelectedPath(){
		return selectedPath;
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getClickCount() == 2) {
			JFileChooser chooser = new JFileChooser();
			chooser.setAcceptAllFileFilterUsed(false);
			chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			chooser.setDialogTitle("选择路径");
			if(startPath != null)
				chooser.setCurrentDirectory(new File(startPath));
			int ok = chooser.showDialog(owner, "选择");
			if (ok == 0) {
				File dir = chooser.getSelectedFile();
				selectedPath = dir.getAbsolutePath();
				if(owner instanceof JTextField)
					((JTextField)owner).setText(selectedPath);
				if(owner instanceof JTextArea){
					String oldvalue = ((JTextArea)owner).getText();
					String plusvalue = selectedPath + ";";
					if(oldvalue == null || !oldvalue.contains(plusvalue))
						((JTextArea)owner).setText(oldvalue + plusvalue);
				}
			}
		}

	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

}
